﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessEntity;
using BusinessLogic;

namespace CentalineWeb
{
    public partial class SheetDetail : System.Web.UI.Page
    {
        private User _userinfo;
        private DataRow order;
        public string DeptListJson = string.Empty;
        ArticleManager am = new ArticleManager();
        protected void Page_Load(object sender, EventArgs e)
        {
            _userinfo = Session["user"] as User;
            var workorder = Request["workorder"];
            order = new VwManager().GetOneByOrder(workorder);
            if (!IsPostBack)
            {
                DeptListJson = new DeptManager().SanJiShiChangDeptListToLevelJson(new DeptManager().GetAllValid());
                
                BindArticle();
                BindDetail();
                BindDdlRepairers();
                BindData(workorder);
                InitControl();
            }
            (this.Master.FindControl("lblTitle") as Label).Text = "工单详情";
        }

        private void BindArticle()
        {
            this.ddlArticle.DataSource = am.ListAll();
            this.ddlArticle.DataTextField = "troubleDesc";
            this.ddlArticle.DataValueField = "articleId";
            this.ddlArticle.DataBind();
        }

        private void BindDetail()
        {
            lblWorkOrder.Text = order["WordOrderId"].ToString();
            txtNumber.Text = order["CompId"].ToString();
            lblApplyTime.Text = Convert.ToDateTime(order["applytime"]).ToString("yyyy-MM-dd HH:mm:ss");
            this.ddlArticle.SelectedIndex = this.ddlArticle.Items.IndexOf(this.ddlArticle.Items.FindByText(order["TroubleDesc"].ToString()));
            //ddlArticle.Text = order["TroubleDesc"].ToString();
            txtTroubleDesc.Text = order["troubledesc2"].ToString();
            txtAddress.Text = order["deptname"].ToString().Substring(order["deptname"].ToString().LastIndexOf("/")+1);
            txtAddress.ToolTip = txtAddress.Text;
            txtEvaluate.Text = order["evaluate"].ToString();
            txtMail.Text = order["email"].ToString();
            txtPhone.Text = order["phone"].ToString();
            txtSolutionDesc.Text = order["SolutionDesc"].ToString();
            lblStaff.Text = order["applyemp"].ToString();
            lblStatusDesc.Text = order["StatusDesc"].ToString();
        }

        private void BindData(string workorder)
        {
            var dt = new VwManager().GetSheetHistoryByworkorder(workorder);
            gvHistory.DataSource = dt;
            gvHistory.DataBind();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            var roleId = _userinfo.RoleId;
            var sheetStatus = order["StatusDesc"].ToString();
            var rm = new RepairManager();
            var hm = new SheetHistoryManager();
            if (roleId == 1)
            {
                rm.UpdateRepByWorkId(order["WordOrderId"].ToString(), Convert.ToInt32(ddlRepairer.SelectedValue));
                hm.AddOne(new SheetHistory()
                {
                    OpDate=DateTime.Now,
                    OperId = _userinfo.Id,
                    OpId = Convert.ToInt32(Operation.ModifySheet),
                    Remark=_userinfo.FullName+"改变该工单维修人员为"+ddlRepairer.SelectedItem.Text,
                    SheetId = new RepairManager().GetIdByWorkId(order["WordOrderId"].ToString())
                });
            }
            if (roleId == 2)
            {
                var op = hdfFlag.Value;
                if (op == "添加进程报告")
                {
                    hm.AddOne(new SheetHistory()
                    {
                        OpDate = DateTime.Now,
                        OperId = _userinfo.Id,
                        OpId = Convert.ToInt32(Operation.AddFixReport),
                        Remark = txtSolutionDesc.Text,
                        SheetId = new RepairManager().GetIdByWorkId(order["WordOrderId"].ToString())
                    });
                }
                else
                {
                    rm.ExecuteSql("update repairs set statusid=3,solutiondesc='" + txtSolutionDesc.Text.Trim() +
                                  "' where wordorderid='" + order["WordOrderId"] + "'");
                    hm.AddOne(new SheetHistory()
                    {
                        OpDate = DateTime.Now,
                        OperId = _userinfo.Id,
                        OpId = Convert.ToInt32(Operation.TroubleSolved),
                        Remark = _userinfo.FullName + "维修完成该工单",
                        SheetId = new RepairManager().GetIdByWorkId(order["WordOrderId"].ToString())
                    });
                }
            }
            if (roleId == 3)
            {
                if (sheetStatus == "3")
                {
                    var sql1= "update repairs set evaluate='"+txtEvaluate.Text+"' where wordorderid='"+order["WordOrderId"].ToString()
                    +"'";
                    rm.ExecuteSql(sql1);
                    hm.AddOne(new SheetHistory()
                    {
                        OpDate = DateTime.Now,
                        OperId = _userinfo.Id,
                        OpId = Convert.ToInt32(Operation.SheetEvaluate),
                        Remark = _userinfo.FullName + "评价了该工单的维修结果",
                        SheetId = new RepairManager().GetIdByWorkId(order["WordOrderId"].ToString())
                    });
                    return;
                }

                var model = new Repairs()
                {
                    CompId = txtNumber.Text.Trim(),
                    ApplyAddres = txtAddress.Text.Trim(),
                    Article = new Article() { ArticleId = Convert.ToInt32(ddlArticle.SelectedValue) },
                    Email = txtMail.Text.Trim(),
                    Phone = txtPhone.Text.Trim(),
                    TroubleDesc = txtTroubleDesc.Text
                };
                var sql =
                    string.Format(
                        "update repairs set compid='{0}',articleid='{1}',phone='{2}',email='{3}',troubledesc='{4}'" +
                        ",ApplyAddres='{5}' where wordorderid='{6}'", model.CompId, model.Article.ArticleId,
                        model.Phone, model.Email, model.TroubleDesc, model.ApplyAddres, order["WordOrderId"].ToString());
                rm.ExecuteSql(sql);

                hm.AddOne(new SheetHistory()
                {
                    OpDate = DateTime.Now,
                    OperId = _userinfo.Id,
                    OpId = Convert.ToInt32(Operation.ModifySheet),
                    Remark = _userinfo.FullName + "修改该工单",
                    SheetId = new RepairManager().GetIdByWorkId(order["WordOrderId"].ToString())
                });
            }
           Response.Redirect("MySheet.aspx");
        }

        private void InitControl()
        {
            var roleId = _userinfo.RoleId;
            var sheetStatus = order["StatusDesc"].ToString();
            if (sheetStatus == "已维修" || sheetStatus == "已取消")//已维修或已取消
            {
                if (roleId == 3)//报修人员可以修改维修后的维修评价
                {
                    txtNumber.Enabled = false;
                    ddlArticle.Enabled = false;
                    txtAddress.Enabled = false;
                    txtTroubleDesc.Enabled = false;
                    txtMail.Enabled = false;
                    txtPhone.Enabled = false;
                    txtEvaluate.Enabled = true;
                    txtSolutionDesc.Enabled = false;
                    ddlRepairer.Enabled = false;
                    btnSubmit.Text = "提交";
                    btnSubmit.Enabled = true;
                    return;
                }
                txtNumber.Enabled = false;
                ddlArticle.Enabled = false;
                txtAddress.Enabled = false;
                txtTroubleDesc.Enabled = false;
                txtMail.Enabled = false;
                txtPhone.Enabled = false;
                txtEvaluate.Enabled = false;
                txtSolutionDesc.Enabled = false;
                ddlRepairer.Enabled = false;
                btnSubmit.Text = "提交";
                btnSubmit.Enabled = false;
                return;
            }
            switch (roleId)
            {
                case 1://管理员在工单未受理和正在维修时可更改维修人员
                    txtNumber.Enabled = false;
                    ddlArticle.Enabled = false;
                    txtAddress.Enabled = false;
                    txtTroubleDesc.Enabled = false;
                    txtMail.Enabled = false;
                    txtPhone.Enabled = false;
                    txtEvaluate.Enabled = false;
                    txtSolutionDesc.Enabled = false;
                    ddlRepairer.Enabled = true;
                    btnSubmit.Text = "确认修改";
                    break;
                case 2://维修人员，不可见未受理工单。自己已受理的只可更改解决方案。自己已维修的不可更改任何
                    txtNumber.Enabled = false;
                    ddlArticle.Enabled = false;
                    txtAddress.Enabled = false;
                    txtTroubleDesc.Enabled = false;
                    txtMail.Enabled = false;
                    txtPhone.Enabled = false;
                    txtEvaluate.Enabled = false;
                    txtSolutionDesc.Enabled = true;
                    txtSolutionDesc.ReadOnly = false;
                    ddlRepairer.Enabled = false;
                    btnSubmit.Text = "添加进程报告";
                    break;
                case 3://报修人员
                    if (sheetStatus == "待受理")//未受理的可更改所有提交保修时填写的信息
                    {
                        btnCancleWork.Visible = true;
                        txtSolutionDesc.Enabled = false;
                        ddlRepairer.SelectedIndex = 0;
                        ddlRepairer.Enabled = false;
                    }
                    if (sheetStatus == "维修中")//已受理时不可更改任何
                    {
                        txtNumber.Enabled = false;
                        ddlArticle.Enabled = false;
                        txtAddress.Enabled = false;
                        txtTroubleDesc.Enabled = false;
                        txtMail.Enabled = false;
                        txtPhone.Enabled = false;
                        txtEvaluate.Enabled = false;
                        txtSolutionDesc.Enabled = false;
                        btnSubmit.Enabled = false;
                        ddlRepairer.Enabled = false;
                        btnSubmit.Visible = false;
                    }
                    break;
            }
        }

        private void BindDdlRepairers()
        {
            var list = new UserManager().GetUsersByroleId(2);
            ddlRepairer.DataTextField = "fullname";
            ddlRepairer.DataValueField = "Id";
            ddlRepairer.DataSource = list;
            ddlRepairer.DataBind();
            ddlRepairer.Items.Insert(0,new ListItem(""));
            this.ddlRepairer.SelectedIndex = this.ddlRepairer.Items.IndexOf(this.ddlRepairer.Items.FindByText(order["repemp"].ToString()));

        }

        protected void btnCancleWork_Click(object sender, EventArgs e)
        {
            new RepairManager().UpdateRepairStatus(order["WordOrderId"].ToString(), 4);
            Page_Load(null, null);
        }
    }
}